<script lang="ts" setup>
import { onMounted, ref, toRaw } from 'vue'
import dayjs from 'dayjs'
import type { Dayjs } from 'dayjs'
import { message } from 'ant-design-vue'
import type { CalendarItem } from '../../types/ant'
import { QAIndexDB } from '@/utils/indexDB'

// 当前年份
const currentYear = ref<number>(dayjs().year())

// 当前年份1-12日历面板
const calendarList = ref<CalendarItem[]>([])
for (let month = 1; month < 13; month++) {
  const value: Dayjs = dayjs(`${currentYear.value}-${month}-01`)
  calendarList.value.push({
    month,
    value,
    validRange: [
      dayjs(value).startOf('month'),
      dayjs(value).endOf('month'),
    ],
  })
}

// 日期格式
const dateFormat = 'YYYY-M-D'
// 选择的日期列表
const selectedList = ref<string[]>([])

// 选择日期回调
function onSelect(value: Dayjs) {
  const date = value.format(dateFormat)
  const index = selectedList.value.indexOf(date)
  if (index !== -1) {
    selectedList.value.splice(index, 1)
  }
  else {
    selectedList.value.push(date)
  }
}

// 保存
function onSubmit() {
  QAIndexDB.setItem('MAKEUP_DAY_LIST', toRaw(selectedList.value))
    .then(() => {
      message.success('保存成功')
    })
    .catch(() => {
      message.error('保存失败')
    })
}

// 获取补班日列表
onMounted(() => {
  QAIndexDB.getItem('MAKEUP_DAY_LIST')
    .then((data: any) => {
      selectedList.value = data || []
    })
})
</script>

<template>
  <a-alert :message="`温馨提示：请选择${currentYear}年补班日`" type="info" show-icon>
    <template #action>
      <a-button type="primary" @click="onSubmit">
        保存
      </a-button>
    </template>
  </a-alert>

  <a-row :gutter="32">
    <a-col v-for="item in calendarList" :key="item.month" :xxl="6" :xl="8" :lg="8" :md="8" :sm="12" :xs="12">
      <a-calendar
        class="calendar" :value="item.value" :valid-range="item.validRange" :fullscreen="false"
        @select="onSelect"
      >
        <template #headerRender>
          <div class="title">
            {{ item.month }}月
          </div>
        </template>
        <template #dateFullCellRender="{ current }">
          <div class="cell" :class="{ active: selectedList.includes(current.format(dateFormat)) }">
            {{ current.format('DD') }}
          </div>
        </template>
      </a-calendar>
    </a-col>
  </a-row>
</template>

<style lang="scss" scoped>
.ant-alert {
  margin-bottom: 24px;
}

.calendar {
  margin-bottom: 32px;

  .title {
    background: #1677ff;
    text-align: center;
    color: #fff;
    line-height: 32px;
    border-radius: 6px 6px 0 0;
  }

  .cell {
    display: inline-block;
    width: 24px;
    height: 24px;
    line-height: 24px;
    border-radius: 4px;
    transition: all 0.2s;
  }

  .ant-picker-cell:not(.ant-picker-cell-disabled) {
    .cell.active {
      color: #fff;
      background: #1677ff;
    }
  }

  :deep(.ant-picker-panel) {
    border: 1px solid #e1e1e1;
  }
}
</style>
